#include "../include/head.h"

// 创建链表
Pnode_list creat_list() {
    Pnode_list head = (Pnode_list)malloc(sizeof(Node_list));
    if (head == NULL) {
       printf("malloc failed\n");
       return NULL;
    }
    head->front = head->next = head;
    return head;
}

// 尾插
int tail_insert(Pnode_list head, Data_type value) {
    //判空 
    if (head == NULL) {
        printf("LIST IS ERROR\n");
        return -1;
    }
    //创建一个新的结点
    Pnode_list newnode = (Pnode_list)malloc(sizeof(Node_list));
    if (newnode == NULL) {
       printf("malloc failed\n");
       return -1;
    }
    memcpy(&newnode->info, &value, sizeof(Data_type));
    
    //找到尾结点
    Pnode_list tailnode = head->front;
   //更改指向
    tailnode->next = newnode;
    newnode->front = tailnode;
    newnode->next = head;
    head->front = newnode;
    return 0;
}

// 计算当前有多少条商品数据
int count_data(Pnode_list head) {
    int count = 0;
    if (head == NULL) {
        printf("list is error\n");
        return 0;
    }
    if (head->next == head) {
        count = 0;
        return count;
    }
    Pnode_list phead = head->next;
    for (count; phead != head; count++) {
        phead = phead->next;
    }
    return count;
}

// 通过商品编号查找结点
Pnode_list id_list_get(Pnode_list head, int value) {
    Pnode_list p = head->next;
    while (p != head) {
        if (p->info.id == value) {
            return p;
        }
        p = p->next;
    }
    return NULL;
}

// 通过商品名称查找结点
Pnode_list string_list_get(Pnode_list head, const char *name) {
    Pnode_list p = head->next;
    while (p != head) {
        
        if (strcmp(p->info.name, name) == 0) {
            return p;
        }
        p = p->next;
    }
    return NULL;
}

// 判断字符串是否为纯数字
int is_all_digits(const char arr[]) {
    if (arr == NULL || *arr == '\0') {
        return 0; // 空字符串
    }
    int len = strlen(arr);
    for (int i = 0; i < len; i++) {
        if (!(arr[i] >= '0' && arr[i] <= '9')) {
            return 0; // 发现非数字字符
        }
    }
    return 1; // 纯数字
}

// 获取要进行操作的结点
Pnode_list get_node(Pnode_list head, const char *input) {
    if (head == NULL || input == NULL) {
        printf("错误：参数不能为空\n");
        return NULL;
    }

    // 检查链表是否为空
    if (head->next == head) {
        printf("商品列表为空\n");
        return NULL;
    }

    Pnode_list phead = NULL;
    
    // 检查输入是否为空字符串
    if (strlen(input) == 0) {
        printf("错误：输入不能为空\n");
        return NULL;
    }

    if (is_all_digits(input)) {
        int id = atoi(input);
        phead = id_list_get(head, id);
    } else {
        phead = string_list_get(head, input);
    }

    if (phead == NULL) {
        printf("未找到匹配的商品 '%s'\n", input);
    }

    return phead; // 可能为NULL
}
// 清理重复数据函数
void remove_duplicates(Pnode_list head) {
    if (head == NULL) return;

    Pnode_list current = head->next;
    while (current != head) {
        Pnode_list runner = current->next;
        while (runner != head) {
            if (runner->info.id == current->info.id ||
                strcmp(runner->info.name, current->info.name) == 0) {
                // 删除重复节点
                Pnode_list temp = runner;
                runner = runner->next;
                temp->front->next = temp->next;
                temp->next->front = temp->front;
                free(temp);
            } else {
                runner = runner->next;
            }
        }
        current = current->next;
    }
}

// 删除商品
int del_list(Pnode_list head, const char *input) {
    Pnode_list node = get_node(head, input);
    if (node == NULL) {
        return -1; // 商品不存在
    }

    // 确认删除
    printf("您确定要删除该商品吗？(y/n)\n");
    char confirm;
    scanf(" %c", &confirm);
    getchar(); // 清除输入缓冲区
    if (confirm == 'y' || confirm == 'Y') {
        // 执行删除
        node->front->next = node->next;
        node->next->front = node->front;
        free(node);
        
        // 更新文件
        write_file(head);
        printf("删除成功\n");
        printf("按回车键继续\n");
        scanf("%*c");
        
    } else {
        printf("取消删除\n");
        printf("按回车键继续\n");
        scanf("%*c");
    }
    return 0;
}

// 遍历链表内数据
int list_show(Pnode_list head) {
    if (head == NULL) {
        printf("链表不存在\n");
        return -1;
    }
    if (head->next == head) {
        printf("链表为空\n");
        return -1;
    }
    printf("遍历链表数据\n");
    Pnode_list phead = head->next;
    while (phead != head) {
        printf("%d  %s  %.2f  %d\n", phead->info.id, phead->info.name, phead->info.price, phead->info.stock);
        phead = phead->next;
    }
    return 0;
}

// 双向循环链表冒泡排序（按商品ID升序）
void bubble_sort_by_id(Pnode_list head) {
    if (head == NULL || head->next == head || head->next->next == head) {
        return; // 空链表或只有一个节点无需排序
    }

    int swapped;
    Pnode_list end = head; // 排序结束位置，初始指向头节点
    Pnode_list curr, next_node;

    do {
        swapped = 0;
        curr = head->next; // 从第一个有效节点开始

        while (curr->next != end) {
            next_node = curr->next;

            if (curr->info.id > next_node->info.id) {
                // 交换两个相邻节点的数据（不改变链接关系）
                Data_type temp = curr->info;
                curr->info = next_node->info;
                next_node->info = temp;
                swapped = 1;
            }
            curr = curr->next;
        }
        end = curr; // 缩小排序范围
    } while (swapped);
}

// 查询商品信息
void find_list(Pnode_list head, const char *input) {
    Pnode_list node = get_node(head, input);
    if (node != NULL) {
        printf("商品编号\t商品名称\t商品价格\t商品数量\n");
        printf("%d\t\t%s\t\t%.2f\t\t%d\n", node->info.id, node->info.name, node->info.price, node->info.stock);
    }
    printf("按回车键继续\n");
    scanf("%*c");
}

// 库存调整
void modify_stock(Pnode_list head, const char *input, int num, int data) {
    Pnode_list phead = get_node(head, input);//创建了一个类型为 Pnode_list 的指针变量 phead
    if (num == 1) { //增加库存
        printf("库存增加成功\n");
        phead->info.stock = phead->info.stock + data;
        outputdata(head);
    } else if (num == 2) { //库存减少
        printf("库存减少成功\n");
        phead->info.stock = phead->info.stock - data;
        outputdata(head);
    } else {
        printf("操作有误\n");
    }
    printf("按回车键继续\n");
    scanf("%*c");
}